package fun.codedesign.jdk.socket.bio;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 通过socket来读写请求
 *
 * @author zengjian
 * @create 2018-04-17 9:21
 * @since 1.0.0
 */
public class BioClient {

    private Socket socket;
    private int count;

    public BioClient() {
        try {
            socket = new Socket("localhost", 8080);
        } catch (IOException e) {
            System.err.println("socket初始化失败：" + e);
        }
    }

    public String sendMessage(String ss) throws IOException {
        OutputStream os = socket.getOutputStream();
        os.write(ss.getBytes("utf-8"));
        os.flush();
        // 接收返回
        InputStream is = socket.getInputStream();
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        return new String(bytes, "utf-8") + (++count);
    }

    public static void main(String[] args) {
        try {
            BioClient client = new BioClient();
            long start = System.currentTimeMillis();
            for (int i = 0; i < 1000000; i++) {
                String resp = client.sendMessage("客户端 say hello" + i);
                System.out.println("接收到服务端返回:" + resp);
            }
            System.out.println(System.currentTimeMillis() - start);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
